package com.my.study.redisson.listener;

import com.my.study.redisson.constant.TaskConstants;
import com.my.study.redisson.model.Message;
import com.my.study.redisson.timer.RedisClientTimer;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 客户端监听器，收到注册消息，进行注册操作
 * 
 * @author: yidujun
 * @create: 2021/11/08 16:15
 */
@Slf4j
@Component
public class ClientRestListener implements MessageListener<Message> {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisClientTimer redisClientTimer;

    @Override
    public void onMessage(CharSequence channel, Message msg) {

        RLock lock = redissonClient.getLock("lock");

        try {
            lock.tryLock(1000, TimeUnit.MILLISECONDS);
            log.info("[ClientRestListener] topic={}, msg={}", channel.toString(), msg.toString());
            if (TaskConstants.CHANNEL_SERVER_REST.equals(channel.toString())) {
                // 获取服务列表 K->ip:port， V->过期时间
                RMap<String, Date> serverList = redissonClient.getMap(TaskConstants.SERVER_LIST);
                for (String s : serverList.keySet()) {
                    log.info("[ClientRestListener]服务列表 ip:port={}", s);
                }

                // 更新所有的服务器编号
                RAtomicLong serverNo = redissonClient.getAtomicLong(TaskConstants.SERVER_NO);
                serverNo.set(0);
                // K->ip:port， V->服务器编号
                RMap<String, Long> serverListNo = redissonClient.getMap(TaskConstants.SERVER_LIST_NO);
                serverListNo.clear();
                for (Map.Entry<String, Date> entry : serverList.entrySet()) {
                    serverListNo.put(entry.getKey(), serverNo.getAndIncrement());
                }

                for (Long no : serverListNo.values()) {
                    log.info("[ClientRestListener]服务列表编号 sererNo={}", no);
                }

                redisClientTimer.doCheck();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.unlock();
        }
    }
}
